import logging
from logging.handlers import RotatingFileHandler

import redis
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy

from config import Config

db = SQLAlchemy()
rs = redis.StrictRedis()


def log_setup(ConfigMode):
    """配置log相关"""
    # 设置等级
    logging.basicConfig(level=ConfigMode.LOG_LEVEL)

    # 设置记录器
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024*1024*100,backupCount=10)
    formatter = logging.Formatter("%(levelname)s %(filename)s: %(lineno)d %(message)s")
    file_log_handler.setFormatter(formatter)
    # 添加记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(ConfigMode):
    """
    创建app程序,接受运行模式参数,DevelopmentConfig, ProductionConfig,来决定启动策略
    返回app, manager, db, rs对象
    """
    log_setup(ConfigMode)
    global db, rs
    app = Flask(__name__)
    app.config.from_object(Config)

    # 创建数据库命令对象
    db = SQLAlchemy(app)
    rs = redis.StrictRedis(host=ConfigMode.REDIS_HOST, port=ConfigMode.REDIS_PORT)

    # 将存储在浏览器的cookie中的session,同步到服务器(目前存在redis)
    Session(app)

    return app